package com.gmail.avereshchaga.db.dao;

import com.gmail.avereshchaga.db.entity.IInvoiceItems;
import com.gmail.avereshchaga.db.entity.InvoiceItemsImpl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 */
@Repository
public class InvoiceItemsDAOImpl implements IInvoiceItemsDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<IInvoiceItems> findByInvoiceId(Long invoiceId) {
        Query q = sessionFactory.getCurrentSession()
                .createQuery("from InvoiceItemsImpl invoice_items where invoice_items.invoice.id = :invoiceId");
        q.setLong("invoiceId", invoiceId);
        List<IInvoiceItems> invoiceItems = q.list();
        return invoiceItems;
    }

    @Override
    public void createInvoiceItems(IInvoiceItems invoiceItem) {
        sessionFactory.getCurrentSession().save(invoiceItem);
    }

    @Override
    public void updateInvoiceItems(IInvoiceItems invoiceItem) {
        sessionFactory.getCurrentSession().update(invoiceItem);
    }

    @Override
    public void deleteInvoiceItems(Long id) {
        Session session = sessionFactory.getCurrentSession();
        Criteria crit = session.createCriteria(InvoiceItemsImpl.class);
        crit.add(Restrictions.eq("id", id));
        IInvoiceItems invoiceItem = (InvoiceItemsImpl) crit.uniqueResult();
        sessionFactory.getCurrentSession().delete(invoiceItem);
    }
}
